from django.conf import settings
from django.db.models.fields.files import ImageFieldFile
from django.forms import ModelForm
from django.forms.widgets import TextInput, Textarea, FileInput, Select
from mitems.models import Item, Comment, Like, CommentLike, Airtime,\
    Share, Follower, UserProfile, Notification, Inquestion, ItemImage
from django import forms
from django.forms.extras.widgets import SelectDateWidget
from django.utils.translation import ugettext as _

class ItemForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        self.fields['description'].label = 'More details'

    class Meta:
        model = Item
        fields = ('message', 'description', 'tag', 'category')
        widgets = {
            'message': TextInput(attrs={'placeholder': 'What just happened?', 'maxlength': '256'}),
            'description': Textarea(attrs={'placeholder': 'Up to 256 characters',
                                           'cols': '20', 'rows': '2'}),
        }


class CommentForm(ModelForm):

    profile = forms.CharField(required=False)

    class Meta:
        model = Comment
        fields = ('comment', 'item')


class LikeForm(ModelForm):

    profile = forms.CharField(required=False)

    class Meta:
        model = Like
        fields = ('item',)


class RepostForm(ModelForm):

    id = forms.IntegerField(widget = forms.HiddenInput)

    class Meta:
        model = Item
        fields = ('id',)

class CommentLikeForm(ModelForm):

    class Meta:
        model = CommentLike
        fields = ('comment',)


class AirtimeForm(ModelForm):

    profile = forms.CharField(required=False)

    class Meta:
        model = Airtime
        fields = ('count', 'item')


class FacebookForm(ModelForm):

    facebook_message = forms.CharField(required=False)
    message = forms.CharField()
    photo = forms.URLField(required=False)
    url = forms.URLField()
    profile = forms.CharField(required=False)

    class Meta:
        model = Share
        fields = ('item',)


class TwitterForm(ModelForm):

    message = forms.CharField(max_length=140)
    profile = forms.CharField(required=False)

    class Meta:
        model = Share
        fields = ('item',)


class FollowForm(ModelForm):

    item = forms.CharField()
    profile = forms.CharField(required=False)

    class Meta:
        model = Follower
        fields = ('follow',)


class ProfileForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ProfileForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].label = 'Profile Photo'
        self.fields['birthday'].label = 'Your birthday is'
        self.fields['interest'].label = 'What are you interested in?'
        self.fields['locale'].label = 'What are you Preferred Language settings?'
        self.fields['mobile_email'].label = '8 on mobile'
        self.fields['email'].label = 'Email'
        self.fields['location'].required = True
        self.fields['location'].choices.pop(0)
        self.fields['location'].choices.insert(0,('', 'Select Location'))

    def clean_avatar(self):
        avatar = self.cleaned_data.get('avatar')
        if isinstance(avatar, ImageFieldFile):
            return avatar
        size = avatar.size
        if size > settings.IMAGE_PROFILE_LIMIT_SIZE:
            raise forms.ValidationError(
                _('Image too big: %.02fMB' % (float(size)/1024/1024)))
        main, sub = avatar.content_type.split('/')
        if not (main == 'image' and sub in ['jpeg', 'gif', 'png']):
            raise forms.ValidationError(_('JPEG, PNG, GIF only.'))
        return avatar

    class Meta:
        model = UserProfile
        fields = ('avatar', 'first_name', 'last_name',
                  'location', 'birthday',
                  'interest', 'locale', 'username',
                  'mobile_email', 'email', 'fb_auto_post')
        widgets = {
            'birthday': SelectDateWidget(years=range(1900,2020)),
            'avatar': FileInput(attrs={'id': 'picture_upload'}),
            'locale': Select(choices=settings.LANGUAGES),
            'mobile_email': TextInput(attrs={'readonly':'readonly'}),
            'username': TextInput(attrs={'readonly':'readonly'}),
        }


class NotificationForm(ModelForm):

    class Meta:
        model = Notification
        exclude=('user',)
#
#    def __init__(self, *args, **kwargs):
#        super(NotificationForm, self).__init__(*args, **kwargs)
#        for field in self.fields.keys():
#           self.fields[field].widget.attrs['disabled'] = True
#           self.fields[field].required = False
#
#    def clean(self):
#        instance = getattr(self, 'instance', None)
#        for field in instance._meta.fields:
#            self.cleaned_data[field.name]  = instance.__dict__.get(field.name)
#        return self.cleaned_data


class InquestionForm(ModelForm):

    class Meta:
        model = Inquestion
        exclude=('user',)


class FilterForm(ModelForm):

    def __init__(self, *args, **kwargs):
        country = kwargs.pop('country', None)
        self.instance = kwargs.get('instance')
        if country != 'all' and self.instance is not None:
            self.instance.location = country
        if country == 'all' and self.instance is not None:
            self.instance.location = ''
        super(FilterForm, self).__init__(*args, **kwargs)
        self.fields['location'].choices.pop(0)
        self.fields['location'].choices.insert(0,('', 'Worldwide'))
        if self.instance is not None and self.instance.location and country != 'all':
            self.fields['location'].widget.attrs = {'class': 'active'}

    class Meta:
        model = UserProfile
        fields = ('location',)


class ItemImageFrom(ModelForm):

    class Meta:
        model = ItemImage
        fields = ('image',)


class FollowFormProfile(ModelForm):

    profile = forms.CharField()

    class Meta:
        model = Follower
        fields = ('follow',)


class FollowFormBroadCast(ModelForm):

    class Meta:
        model = Follower
        fields = ('follow',)


class GoogleEmail(forms.Form):

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices',None)
        super(GoogleEmail, self).__init__(*args, **kwargs)
        if choices:
            self.fields['emails'].choices = choices

    emails = forms.MultipleChoiceField(choices=[], widget=forms.CheckboxSelectMultiple, required=True)
    message = forms.CharField(required=True, widget=forms.Textarea(
                                  attrs={'class':'user_input', 'cols':'45',
                                         'id':'message', 'rows':'3', 'style':'width: 350px'}
                                  )
    )